import uuid
import os, sys, random, string
from flask import Blueprint, render_template, request, url_for, redirect, session

from sqlalchemy import and_

from exts import db
from utils.md5 import md5
from apps.user.models import User
import os

user_bp = Blueprint('user', __name__)


# 注册
# @user_bp.route('/register', methods=['GET', 'POST'])
# def register():
#     if request.method == 'GET':
#         return render_template('user/register.html')
#     phone = str(request.form.get('phone'))
#     username = str(request.form.get('phone'))
#     password = request.form.get('password')
#     # 如果任意为空，都返回
#     if not username or not password or not phone:
#         # print(request.form)
#         # print(username, '------------')
#         return render_template('user/register.html', error='无效数据')
#     # 保存数据库
#     # 密码加密
#     password = md5(password)[0:20]
#     user = User()
#     user.username = username
#     user.password = password
#     user.phone = phone
#     # 添加并提交
#     db.session.add(user)
#     db.session.commit()
#     url = url_for('user.login')
#     return redirect(url)


@user_bp.route('/', methods=['GET', 'POST'])
def login():
    if request.method == 'GET':
        # 获取数据，进行查询
        return render_template('user/login.html', error='无效数据')
    phone = str(request.form.get('phone'))
    password = request.form.get('password')
    ret = User.query.filter(User.phone == phone, User.is_delete == False).first()
    if not ret:
        return render_template('user/login.html', error='无效数据')
    password = md5(password)[0:20]
    ret = User.query.filter(and_(User.phone == phone, User.password == password)).first()
    if not ret:
        return render_template('user/login.html', error='无效数据')
    session['username'] = ret.username

    return redirect(url_for('admin.admin_index'))


@user_bp.route('/logout', methods=['GET', 'POST'])
def logout():
    # 1。 cookie的方式
    # response = redirect(url_for('user.index'))
    # 通过response对象的delete_cookie(key),key就是要删除的cookie的key
    # response.delete_cookie('uid')
    # 2。session的方式
    # del session['uid']
    session.clear()
    return redirect(url_for('user.login'))

# yaml数据展示

#
# @user_bp.route('/view_configure/')
# def view_configure():
#     import yaml, json
#     # file_paths = os.environ.get("LYH_CONFIG") + "/"
#     yaml_config = dict()
#     json_config = dict()
#     params = list()
#     actions = list()
#     try:
#         # current_path = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
#         current_path = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
#
#         print(current_path, '-----------')
#         print(current_path + r"\ros_config.yaml", '-----------')
#         # D:\pythonProject\flask_admin\ros_config.yaml
#         # ros_config.yaml配置
#         yaml.default_style = "\""
#         with open(current_path + r"\ros_config.yaml", 'r', encoding='utf-8') as f:
#             yaml_config = yaml.load(f, Loader=yaml.FullLoader)
#
#         for i in yaml_config.items():
#             value = str(i[1]).replace("\'", "\"").replace("True", "true").replace("False", "false")
#             temp = [i[0], value]
#             params.append(temp)
#
#         return render_template('cms/view_configure.html', params=params)
#
#     except Exception as e:
#         return render_template('cms/view_configure.html', params=[["error", str(e)]])
#
#
# @user_bp.route('/save_configure', methods=['POST'])
# def save_configure():
#     import yaml, json
#     print('1')
#     data = {
#         "msg": "ok",
#         "code": 0
#     }
#
#     try:
#         req_data = request.form.to_dict()
#         for key in req_data:
#             req_data[key] = json.loads(req_data[key])
#         current_path = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
#         # with open(current_path + "/configureServer/config/ros_config.yaml", 'w') as f:
#         with open(current_path + r"\ros_config.yaml", 'w') as f:
#             yaml.dump(req_data, f, allow_unicode=True, sort_keys=False)
#         response = json.dumps(data)
#         return response, 200, {"Content-Type": "application/json"}
#     except BaseException as e:
#         # print e
#
#         data["msg"] = str(e)
#         data["code"] = 500
#         response = json.dumps(data)
#
#         return response, 500, {"Content-Type": "application/json"}
